<template>
  <Card dis-hover :bordered="false">
    <Row class="ivu-mb-16">
      <Col>
        <Button
          type="primary"
          @click="handleAdd"
          v-hasC="{
            name: 'v1-buss-tool-water-create',
            flag: 'v1/buss/tool-water/create',
          }"
          >新增</Button
        >
      </Col>
    </Row>

    <Table
      :columns="columns"
      :data="list"
      @on-sort-change="sortChange"
      :loading="loading"
      :max-height="tableHeigth"
    >
      <template #text="{ row }">
        <img :src="row.file_url" alt="" v-if="row.type == 2" height="40" />
        <span v-else>{{ row.text }}</span>
      </template>

      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-buss-tool-water-update',
            flag: 'v1/buss/tool-water/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-tool-water-update',
            flag: 'v1/buss/tool-water/update',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-buss-tool-water-delete',
            flag: 'v1/buss/tool-water/delete',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
      @on-visible-change="
        (e) => {
          !e && haddleCancel();
        }
      "
    >
      <Form ref="create" :model="formInfo" :rules="rules" :label-width="80">
        <FormItem label="项目" prop="project_id" required>
          <Select placeholder="项目" v-model="formInfo.project_id">
            <Option
              v-for="item in projectList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="水印类型" prop="type" required>
          <RadioGroup v-model="formInfo.type">
            <Radio
              :label="item.value"
              v-for="item in typeList"
              :key="item.value"
              >{{ item.label }}</Radio
            >
          </RadioGroup>
        </FormItem>
        <FormItem label="内容" prop="text" v-if="formInfo.type == 1" required>
          <Input placeholder="内容" v-model="formInfo.text" />
        </FormItem>
        <FormItem label="上传图片" prop="file" v-else>
          <Upload
            action=""
            :accept="supportType"
            :show-upload-list="false"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
          >
            <Button type="primary" :loading="loadingUpload">上传</Button>
            <Tooltip
              :max-width="300"
              placement="top"
              :content="'支持文件格式：' + supportType"
              class="ivu-ml-8"
            >
              <Icon type="ios-alert-outline" size="20" color="#2db7f5" />
            </Tooltip>
          </Upload>
          <div class="imgList1 ivu-mt-16">
            <div
              class="demo-upload-list"
              v-for="(item, index) in files"
              :key="item"
            >
              <img :src="item" fit="cover" width="40" height="40" />
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click="handleView(item)"></Icon>
                <Icon
                  type="ios-trash-outline"
                  @click="handleImgRemove()"
                ></Icon>
              </div>
            </div>
          </div>
        </FormItem>
        <FormItem label="透明度" prop="alpha">
          <Slider v-model="formInfo.alpha" :min="20" :max="80"></Slider>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="haddleCancel">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  toolWaterList,
  createToolWater,
  toolWaterInfo,
  updateToolWater,
  delToolWater,
  uploadFile,
} from "@api/watermark.js";
export default {
  name: "watermark",
  data() {
    return {
      tableHeigth: document.body.clientHeight - 280,
      addModal: false,
      edit: true,
      loading: false,
      btnLoading: false,
      loadingUpload: false,
      typeList: [],
      projectList: [],
      params: {
        current: 1,
        size: 10,
      },
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns: [
        {
          key: "project_name",
          title: "项目",
        },
        {
          slot: "text",
          title: "内容",
        },
        {
          key: "alpha",
          title: "透明度",
        },
        {
          key: "type_str",
          title: "类型",
        },
        {
          key: "created_at_str",
          title: "创建时间",
        },
        {
          key: "created_member_name",
          title: "创建人",
        },
        {
          slot: "action",
          title: "操作",
          width: 110,
          fixed: "right",
        },
      ],
      list: [],
      formInfo: {
        id: "",
        project_id: "",
        type: 1,
        text: "",
        file: "",
        alpha: 20,
      },
      rules: {
        project_id: [{ required: true, message: "请选择项目" }],
        type: [{ required: true, message: "请选择类型" }],
        text: [{ required: true, message: "请输入水印文字" }],
        file: [{ required: true, message: "请上传水印图片" }],
      },
      controller: null,
      supportType: "",
      files: [],
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    handleBeforeUpload(e) {
      if (e.size > 1 * 1024 * 1024) {
        this.$Message.error("文件大小不能超过1M");
        return false;
      }
      this.loadingUpload = true;
      this.controller = new AbortController();
      this.files = [];
      this.formInfo.file = null;
      uploadFile({ site: "tool", module: "water", file: e }, this)
        .then((res) => {
          this.formInfo.file = res.file;
          this.files = [res.url];
          this.loadingUpload = false;
        })
        .catch((res) => {
          this.loadingUpload = false;
        });
      return false;
    },
    haddleCancel() {
      if (this.controller) {
        this.controller.abort();
      }
      this.btnLoading = false;
      this.loadingUpload = false;
      this.addModal = false;
    },
    handleUploadError(error) {
      this.$Message.error(error);
      this.loadingUpload = false;
    },
    handleImgRemove() {
      this.formInfo.file = null;
      this.files = [];
    },
    handleView(url) {
      this.$hevueImgPreview({
        multiple: false,
        url: url,
      });
    },
    sortChange(e) {
      this.params.order_column = e.key.replace(/_str$/, "");
      this.params.order_sort = e.order;
      this.getData();
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          delToolWater({ id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    getWaterInfo(id) {
      this.formInfo = {
        project_id: "",
        type: 1,
        text: "",
        file: "",
        alpha: 20,
      };
      this.$refs.create.resetFields();
      toolWaterInfo({ id }).then((res) => {
        this.projectList = res.condition.project;
        this.typeList = res.condition.type;
        this.supportType = res.support_image_type;
        if (id > 0) {
          this.files = res.file_url ? [res.file_url] : [];
          this.formInfo = {
            id: res.id,
            project_id: res.project_id,
            type: res.type,
            text: res.text,
            file: res.file,
            alpha: res.alpha,
          };
        }
      });
    },
    handleAdd() {
      this.getWaterInfo(0);
      this.addModal = true;
      this.edit = true;
    },
    handleEdit(info) {
      this.getWaterInfo(info.id);
      this.addModal = true;
      this.edit = false;
    },
    getData() {
      this.loading = true;
      const params = {
        pageSize: this.params.size,
        page: this.params.current,
      };
      toolWaterList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addForm() {
      this.btnLoading = true;
      const params = {
        project_id: this.formInfo.project_id,
        type: this.formInfo.type,
        text: this.formInfo.text,
        file: this.formInfo.file,
        alpha: this.formInfo.alpha,
      };
      if (this.edit) {
        createToolWater(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.addModal = false;
            this.btnLoading = false;
            this.params.current = 1;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateToolWater(Object.assign({}, params, { id: this.formInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addForm();
        } else {
          this.addModal = true;
          return;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.imgList {
  width: 100%;
  white-space: nowrap;
  overflow: auto;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
